// http.js用来做请求封装的

// 用于做请求的进度条的
import NProgress from "nprogress";

const BASE_URL = "http://www.pudge.wang:3080/api";

const http = {
  get(url, params) {
    // params {a: 3, b: 4}
    if (params) {
      const arr = Object.keys(params); // arr: ["a", "b"]
      const arr2 = arr.map((item) => item + "=" + params[item]); // ['a=3', 'b=4']
      const str = arr2.join("&"); // "a=3&b=4"
      url += "?" + str;
      // url -> url + "?a=3&b=4"
    }

    return fetch(BASE_URL + url)
      .then((response) => response.json())
      .then((res) => {
        if (res.status === 0) {
          return res;
        }
      });
  },
  // 一般来说，post请求习惯用data表示参数的形参，get请求习惯使用params
  post(url, data) {
    // console.log(data);
    NProgress.start();
    return fetch(BASE_URL + url, {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        NProgress.done();
        return response.json();
      })
      .then((res) => {
        if (res.status === 0) {
          return res;
        }
      });
  },
};

export default http;
